#include <stdint.h>

#include "bsp_protocol.hpp"
#include "strutil.hpp"
#include "bsp_uart.h"
#include "log.h"
#include "stimer.h"
#include <math.h>
#include "servo.h"
#include "wifi_connect.hpp"
#include "task_main.h"
#include "bsp_flash_config.h"

extern class wifiConnect wifiJAP;
#define debug_printf(fmt, ...) UARTx_Printf(&huart1, fmt, ##__VA_ARGS__)
uint8_t SYSSU_Buf[10]; // 解析器的缓存,Split分割后的数据的引索存储到这里
StrUtil SYSSU("SYS:", ',', ";", SYSSU_Buf, sizeof(SYSSU_Buf), NULL, 0);
int sys_print_id = -1;



void sys_print_info(const void *arg)
{
#if 0
	UART_HandleTypeDef *huart = (UART_HandleTypeDef *)arg;
	const float Vref = 2.5f;
	//	const float Vcc = 3.3f;
	//	float ADC_NTC1      = ADC1Buf[0] * Vref / 4095; //PC1
	//	float ADC_NTC2      = ADC1Buf[1] * Vref / 4095; //PC2
	//	float ADC_NTC3      = ADC1Buf[2] * Vref / 4095; //PC3
	//	float R1            = ADC_NTC1/(Vcc-ADC_NTC1); // V2/V1 = R2/R1 ,V1+V2=Vcc => R2 = V2/(Vcc-V2)*R1
	//	float R2            = ADC_NTC2/(Vcc-ADC_NTC2); // V2/V1 = R2/R1 ,V1+V2=Vcc => R2 = V2/(Vcc-V2)*R1
	//	float R3            = ADC_NTC3/(Vcc-ADC_NTC3); // V2/V1 = R2/R1 ,V1+V2=Vcc => R2 = V2/(Vcc-V2)*R1
	float T1 = ntc_convert_temp(ADC1Buf[0]);
	float T2 = ntc_convert_temp(ADC1Buf[1]);
	float T3 = ntc_convert_temp(ADC1Buf[2]);
	float ADC_HV_V = (ADC1Buf[3] * Vref / 4095 * 1000 * 222 / 0.7568f * 0.9885f - 300) * 1.00735f; // PB0
	float ADC_HV_I = (ADC1Buf[4] * Vref / 4095 * 1000 / 27 / 0.01f * 0.2093f - 950) * 7.7f;		   // PB1 +输出 / -输入到高侧

	float ADC_HV_IPA_I = ADC2Buf[0] * Vref / 4095 * 1000 / 29.4f * 100;				 // PB2
	float ADC_LV_IPA_I = ADC2Buf[1] * Vref / 4095 * 1000 / 19.5f * 200;				 // PB12
	float ADC_LV_I = (ADC2Buf[2] * Vref * 5.920006f - 30000) * 1.61f * 0.97f;		 // PB14 -是输出
	float ADC_LV_V = ADC2Buf[3] * Vref / 4095 * 1000 * 31.7f * 1.02f * 1.302f - 250; // PB15
	UARTx_Printf(huart, "HVII;LVII(mV):%.0f,%.0f,%.0f,%.0f,%.0f,%.0f,%.2f,%.2f,%.2f\n\r",
				 ADC_HV_V, ADC_HV_I, ADC_HV_IPA_I,
				 ADC_LV_V, ADC_LV_I, ADC_LV_IPA_I,
				 T1, T2, T3);
#endif
}

void sys_print_info_start(uint16_t invert, UART_HandleTypeDef *huart)
{
	if (sys_print_id == -1)
	{
		sys_print_id = stimer_create_task(sys_print_info, invert, 1, 1);
		if (sys_print_id >= hstimer.size)
		{
			debug_printf("sys_print_info_start error\n\r");
			sys_print_id = -1;
		}
		stimer_task_start(sys_print_id, STIMER_TASK_LOOP, huart);
	}
}

void sys_print_info_stop(void)
{
	stimer_task_stop(sys_print_id);
	sys_print_id = -1;
}


int SYS_CMD(UART_HandleTypeDef *huart, uint8_t *pdata, uint16_t len)
{
	/*
	 * @CMD SYS:Log,level,[level]\n\r
	 * @param\n\r
	   level:   LOG_LEVEL_NONE=0,\n\r
				LOG_LEVEL_DEBUG=1,\n\r
				LOG_LEVEL_INFO=2,\n\r
				LOG_LEVEL_WARN=3,\n\r
				LOG_LEVEL_ERROR=4,\n\r
				LOG_LEVEL_FATAL=5,\n\r
	*/
	uint32_t temp;
	uint8_t ok_flag = 0;
	if (huart == NULL || pdata == NULL || len < 5)
	{
		return 0;
	}
	SYSSU.setSrcAddress(pdata, len);
	if (SYSSU.parse() == 0)
	{
		return 0;
	}
	char *str = SYSSU.getStr(0);
	switch (*str)
	{
	case 'H':
	case 'h':
		temp = 0;
		if (SYSSU.strCmp(0, "help"))
		{
			UARTx_Printf(huart, "@CMD[%d] SYS:Log,help;\n\r", temp++);
			UARTx_Printf(huart, "@CMD[%d] SYS:debug,print,<time>;\n\r", temp++);
			// UARTx_Printf(huart, "@CMD[%d] SYS:power,on/off;\n\r", temp++);
			UARTx_Printf(huart, "@CMD[%d] SYS:wifi,cfg,<ssid>,<pwd>;\n\r", temp++);
			UARTx_Printf(huart, "@CMD[%d] SYS:wifi,stop/start;\n\r", temp++);
			UARTx_Printf(huart, "@CMD[%d] SYS:mqtt,cfg,<clientID>,<userName><pwd>;\n\r", temp++);
			UARTx_Printf(huart, "@CMD[%d] SYS:mqtt,cfgid,<float>,<int>,<bool>;\n\r", temp++);
			ok_flag = 1;
		}
		
	
	case 'd': // SYS:debug,print,<time>;
		if (SYSSU.strCmp(0, "debug"))
		{
			if (SYSSU.strCmp(1, "print"))
			{
				if (sys_print_id == -1)
				{
					sys_print_info_start(SYSSU.getInt(2), huart);
					ok_flag = 1;
				}
				else
				{
					sys_print_info_stop();
					ok_flag = 1;
				}
			}
		}
		break;
	case 'L':
		if (SYSSU.strCmp(0, "Log"))
		{
			switch (SYSSU.getStr(1)[0])
			{
			case 'h':

				break;
			case 'H':
				UARTx_Print(huart, "     * @CMD SYS:Log,level,[level]\n\r     * @param\n\r       level:   LOG_LEVEL_NONE=0,\n\r                LOG_LEVEL_DEBUG=1,\n\r                LOG_LEVEL_INFO=2,\n\r                LOG_LEVEL_WARN=3,\n\r                LOG_LEVEL_ERROR=4,\n\r                LOG_LEVEL_FATAL=5,\n\r");
				ok_flag = 1;
				break;
			case 'l': // set
				temp = SYSSU.getInt(2);
				if (temp < 6)
				{
					log_set_level(temp);
					UARTx_Printf(huart, "set log level:%d ok\n\r", temp);
					ok_flag = 1;
				}
				break;
			default:
				break;
			}
		}
		break;
	case 'w':
		if (SYSSU.strCmp(0, "wifi"))
		{
			if (SYSSU.strCmp(1, "stop")) // SYS:wifi,stop;
			{
				wifiJAP.stop_connect();
				ok_flag = 1;
			}
			else if (SYSSU.strCmp(1, "start")) // SYS:wifi,start;
			{
				wifiJAP.start_connect();
				ok_flag = 1;
			}
			else if (SYSSU.strCmp(1, "cfg")) // SYS:wifi,cfg,<ssid>,<psd>;
			{
				int len1 = strlen(SYSSU.getStr(2));
				int len2 = strlen(SYSSU.getStr(3));
				if (len1 > 32 || len2 > 32)
				{
				    debug_printf("wifi cfg error, ssid or password too length.\n\r");
				}
				else
				{
					memcpy(sysCfgInfo.wifi_ssid, SYSSU.getStr(2), len1);
					sysCfgInfo.wifi_ssid[len1] = '\0';
					memcpy(sysCfgInfo.wifi_pwd, SYSSU.getStr(3), len2);
					sysCfgInfo.wifi_pwd[len2] = '\0';
					bsp_flash_config_save_start();
					debug_printf("new wifi cfg ssid:\"%s\", pwd:\"%s\"\n\r", sysCfgInfo.wifi_ssid, sysCfgInfo.wifi_pwd);
					ok_flag = 1;
				}
			}
		}
		break;
	case 's':
		if (SYSSU.strCmp(0, "servo"))
		{
			if (SYSSU.strCmp(1, "angle")) // SYS:servo,start;
			{
				servo1.writeEnable(1);
				servo1.writeAngle(SYSSU.getDouble(2));
				ok_flag = 1;
			}
			else if (SYSSU.strCmp(1, "value")) // SYS:servo,stop;
			{
				servo1.writeEnable(1);
				servo1.writeValue(SYSSU.getInt(2));
				ok_flag = 1;
			}
			else if (SYSSU.strCmp(1, "stop"))
			{
				servo1.writeEnable(0);
				ok_flag = 1;
			}
		}
		break;
	case 'm':
		if (SYSSU.strCmp(0, "mqtt"))
		{
			if (SYSSU.strCmp(1, "cfg"))
			{
				int len1 = strlen(SYSSU.getStr(2));
				int len2 = strlen(SYSSU.getStr(3));
				int len3 = strlen(SYSSU.getStr(4));
				if (len1 > 20 || len2 > 20 || len3 > 20)
				{
					debug_printf("mqtt cfg error, server or user or password too length.\n\r");
				}
				else
				{
					memcpy(sysCfgInfo.mqtt_client_id, SYSSU.getStr(2), len1);
					sysCfgInfo.mqtt_client_id[len1] = '\0';
					memcpy(sysCfgInfo.mqtt_username, SYSSU.getStr(3), len2);
					sysCfgInfo.mqtt_username[len2] = '\0';
					memcpy(sysCfgInfo.mqtt_password, SYSSU.getStr(4), len3);
					sysCfgInfo.mqtt_password[len3] = '\0';
					debug_printf("new mqtt cfg: \n\rclient_id:\"%s\"\n\r", sysCfgInfo.mqtt_client_id);
					debug_printf("username:\"%s\"\n\r", sysCfgInfo.mqtt_username);
					debug_printf("password:\"%s\"\n\r", sysCfgInfo.mqtt_password);
					bsp_flash_config_save_start();
					ok_flag = 1;
				}
			}
			else if (SYSSU.strCmp(1, "cfgID"))
			{
				sysCfgInfo.mqtt_id_openLockAngle = SYSSU.getInt(2);
				sysCfgInfo.mqtt_id_autoCloseTime = SYSSU.getInt(3);
				sysCfgInfo.mqtt_id_lockCtrl = SYSSU.getInt(4);
				debug_printf("mqtt cfgID: openLockAngle:%d, autoCloseTime:%d, lockCtrl:%d\n\r",
				             sysCfgInfo.mqtt_id_openLockAngle,
							 sysCfgInfo.mqtt_id_autoCloseTime,
							 sysCfgInfo.mqtt_id_lockCtrl);
				bsp_flash_config_save_start();
				ok_flag = 1;
			}
		}
		break;
	default:
		break;
	}
	if (ok_flag)
	{
		Beep(50);
		UARTx_Print(huart, "OK\n\r");
	}
	return ok_flag;
}
